<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商家中心 - 新商城</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
    <header class="bg-white shadow-md">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="text-2xl font-bold text-blue-600">新商城</div>
            <div class="flex items-center space-x-6">
                <div class="relative">
                    <button id="merchantMenuBtn" class="flex items-center space-x-2 focus:outline-none">
                        <i class="fa fa-user-circle text-xl text-gray-600"></i>
                        <span id="merchantnameDisplay" class="text-gray-700"></span>
                        <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                    </button>
                    <div id="merchantMenu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 hidden z-10">
                        <a href="#" id="editShopBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                            <i class="fa fa-edit mr-2"></i>店铺资料
                        </a>
                        <a href="#" id="logoutBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                            <i class="fa fa-sign-out mr-2"></i>退出登录
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <div class="flex flex-col md:flex-row gap-6">
            <!-- 侧边导航 -->
            <div class="w-full md:w-64 bg-white rounded-lg shadow-md p-4">
                <nav class="space-y-1">
                    <a href="#" class="nav-link active block px-4 py-3 rounded-md bg-green-50 text-green-600 font-medium">
                        <i class="fa fa-home mr-3"></i>首页
                    </a>
                    <a href="#" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-shopping-bag mr-3"></i>我的商品
                    </a>
                    <a href="#" class="nav-link block px-4 py-3 rounded-md text-gray-700 hover:bg-gray-100 font-medium">
                        <i class="fa fa-list-alt mr-3"></i>订单管理
                    </a>
                </nav>
            </div>

            <!-- 主内容区 -->
            <div class="flex-1 space-y-6">
                <!-- 店铺信息 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h2 class="text-2xl font-bold" id="shopName"></h2>
                        <button id="addGoodBtn" class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition">
                            <i class="fa fa-plus mr-2"></i>上架商品
                        </button>
                    </div>
                    <p class="text-gray-600 mb-2" id="shopDesc"></p>
                    <p class="text-gray-600" id="shopAddress"></p>
                </div>

                <!-- 商品列表 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-bold">我的商品</h2>
                    </div>
                    
                    <div id="goodsList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <!-- 商品将通过JavaScript动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 上架商品模态框 -->
    <div id="addGoodModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">上架商品</h3>
                <button id="closeAddGoodModalBtn" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <form id="addGoodForm" class="space-y-4">
                <!-- <div>
                    <label for="goodId" class="block text-gray-700 mb-1">商品ID</label>
                    <input type="number" id="goodId" class="w-full px-3 py-2 border border-gray-300 rounded-md" required>
                </div> -->
                
                <div>
                    <label for="goodName" class="block text-gray-700 mb-1">商品名称</label>
                    <input type="text" id="goodName" class="w-full px-3 py-2 border border-gray-300 rounded-md" required>
                </div>
                
                <div>
                    <label for="goodPrice" class="block text-gray-700 mb-1">商品价格（元）</label>
                    <!-- 限制为数字类型，最多两位小数 -->
                    <input type="number" id="goodPrice" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-md" 
                        step="0.01" min="0.01" required
                        placeholder="请输入商品价格,例如:9.99">
                </div>
                
                <div>
                    <label for="goodDesc" class="block text-gray-700 mb-1">商品描述</label>
                    <textarea id="goodDesc" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md"></textarea>
                </div>
                
                <button type="submit" class="w-full py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition">
                    确认上架
                </button>
            </form>
        </div>
    </div>

    <!-- 编辑店铺资料模态框 -->
    <div id="editShopModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold">编辑店铺资料</h3>
                <button id="closeEditShopModalBtn" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            
            <form id="editShopForm" class="space-y-4">
                <input type="hidden" id="editMerchantId">
                
                <div>
                    <label for="editUsername" class="block text-gray-700 mb-1">用户名</label>
                    <input type="text" id="editUsername" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editPassword" class="block text-gray-700 mb-1">密码 (不修改请留空)</label>
                    <input type="password" id="editPassword" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editShopname" class="block text-gray-700 mb-1">店铺名称</label>
                    <input type="text" id="editShopname" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editContactPerson" class="block text-gray-700 mb-1">联系人</label>
                    <input type="text" id="editContactPerson" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editPhone" class="block text-gray-700 mb-1">联系电话</label>
                    <input type="tel" id="editPhone" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editAddress" class="block text-gray-700 mb-1">店铺地址</label>
                    <input type="text" id="editAddress" class="w-full px-3 py-2 border border-gray-300 rounded-md">
                </div>
                
                <div>
                    <label for="editShopDesc" class="block text-gray-700 mb-1">店铺描述</label>
                    <textarea id="editShopDesc" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md"></textarea>
                </div>
                
                <button type="submit" class="w-full py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition">
                    保存修改
                </button>
            </form>
        </div>
    </div>

    <footer class="bg-gray-800 text-white py-8 mt-16">
        <div class="container mx-auto px-4 text-center">
            <p>© 2025 新商城 版权所有</p>
        </div>
    </footer>

    <script>
        // 当前登录商家信息
        let currentMerchant = null;

        // 页面加载完成后初始化
        window.addEventListener('DOMContentLoaded', async () => {
            // 检查登录状态
            const merchantStr = localStorage.getItem('merchant');
            if (!merchantStr) {
                window.location.href = 'merchant-login.html';
                return;
            }
            
            currentMerchant = JSON.parse(merchantStr);
            
            // 显示商家信息
            document.getElementById('merchantnameDisplay').textContent = currentMerchant.username;
            document.getElementById('shopName').textContent = currentMerchant.shopname || '我的店铺';
            document.getElementById('shopDesc').textContent = currentMerchant.shop_desc || '暂无店铺描述';
            document.getElementById('shopAddress').textContent = currentMerchant.address || '暂无店铺地址';
            
            // 加载商品列表
            await loadMerchantGoods();
            
            // 绑定事件
            bindEvents();
        });

        // 绑定事件
        function bindEvents() {
            // 商家菜单切换
            document.getElementById('merchantMenuBtn').addEventListener('click', () => {
                document.getElementById('merchantMenu').classList.toggle('hidden');
            });
            
            // 点击其他区域关闭商家菜单
            document.addEventListener('click', (e) => {
                const merchantMenuBtn = document.getElementById('merchantMenuBtn');
                const merchantMenu = document.getElementById('merchantMenu');
                
                if (!merchantMenuBtn.contains(e.target) && !merchantMenu.contains(e.target)) {
                    merchantMenu.classList.add('hidden');
                }
            });
            
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', () => {
                localStorage.removeItem('merchant');
                window.location.href = 'index.html';
            });
            
            // 编辑店铺资料按钮
            document.getElementById('editShopBtn').addEventListener('click', () => {
                fillEditShopForm();
                document.getElementById('editShopModal').classList.remove('hidden');
            });
            
            // 关闭编辑店铺资料模态框
            document.getElementById('closeEditShopModalBtn').addEventListener('click', () => {
                document.getElementById('editShopModal').classList.add('hidden');
            });
            
            // 打开上架商品模态框
            document.getElementById('addGoodBtn').addEventListener('click', () => {
                document.getElementById('addGoodModal').classList.remove('hidden');
                document.getElementById('addGoodForm').reset();
            });
            
            // 关闭上架商品模态框
            document.getElementById('closeAddGoodModalBtn').addEventListener('click', () => {
                document.getElementById('addGoodModal').classList.add('hidden');
            });
            
            // 上架商品表单提交
            document.getElementById('addGoodForm').addEventListener('submit', async (e) => {
                e.preventDefault();
    
                // 获取表单输入值
                const goodName = document.getElementById('goodName').value;
                const priceInput = parseFloat(document.getElementById('goodPrice').value); // 元单位
                const goodDesc = document.getElementById('goodDesc').value;
                
                // 验证价格格式（确保最多两位小数）
                if (isNaN(priceInput) || priceInput <= 0) {
                    alert('请输入有效的价格');
                    return;
                }
                if (priceInput.toString().split('.')[1]?.length > 2) {
                    alert('价格最多只能保留两位小数');
                    return;
                }
    
                // 转换为分单位（四舍五入避免浮点数精度问题）
                const priceInCent = Math.round(priceInput * 100);
    
                // 构造请求数据
                const goodData = {
                    goodname: goodName,
                    price: priceInCent, // 传入分单位
                    good_desc: goodDesc
                };
    
                // 发送请求到后端
                try {
                    const response = await fetch('http://localhost:8080/api/goods/add?merchantId=' + currentMerchant.id, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(goodData)
                    });
                    const result = await response.json();
                    if (result.success) {
                        alert('商品上架成功');
                        // 刷新商品列表等操作
                    } else {
                        alert('商品上架失败：' + result.message);
                    }
                } catch (error) {
                    console.error('提交失败', error);
                    alert('提交失败，请重试');
                }
            });
            
            // 编辑店铺资料表单提交
            document.getElementById('editShopForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                await submitEditShop();
            });
            
            // 导航链接切换
            document.querySelectorAll('.nav-link').forEach(link => {
                link.addEventListener('click', async(e) => {
                    e.preventDefault();
                    
                    // 移除所有active类
                    document.querySelectorAll('.nav-link').forEach(l => {
                        l.classList.remove('active', 'bg-green-50', 'text-green-600');
                        l.classList.add('text-gray-700');
                    });
                    
                    // 给当前点击的添加active类
                    e.target.classList.add('active', 'bg-green-50', 'text-green-600');
                    e.target.classList.remove('text-gray-700');
                    
                    // 根据点击的导航切换内容
                    const text = e.target.textContent.trim();
                    if (text.includes('我的商品')) {
                        await loadMerchantGoods();
                    } else if (text.includes('订单管理')) {
                        await loadMerchantOrders();
                    } else if (text.includes('首页')) {
                        await loadMerchantGoods();
                    }
                });
            });
        }

        // 加载商家商品列表
        async function loadMerchantGoods() {
            try {
                const response = await fetch('http://localhost:8080/api/goods/merchant/owned', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id: currentMerchant.id }) // 传递商家ID（匹配MerchantUser的id字段）
});
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const goodsListElement = document.getElementById('goodsList');
                    goodsListElement.innerHTML = '';
                    
                    if (result.data.length === 0) {
                        goodsListElement.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">您暂无上架的商品</div>';
                        return;
                    }
                    
                    result.data.forEach(good => {
                        const goodCard = document.createElement('div');
                        goodCard.className = 'border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition';
                        goodCard.innerHTML = `
                            <div class="p-4">
                                <h3 class="font-bold text-lg mb-2">${good.goodname}</h3>
                                <p class="text-gray-600 text-sm mb-2">${good.good_desc || '无描述'}</p>
                                <p class="text-red-600 font-bold mb-4">¥${(good.price / 100).toFixed(2)}</p>
                                <button class="remove-good-btn w-full py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition" 
                                        data-goodid="${good.goodid}">
                                    <i class="fa fa-trash mr-2"></i>下架商品
                                </button>
                            </div>
                        `;
                        goodsListElement.appendChild(goodCard);
                    });
                    
                    // 绑定下架商品按钮事件
                    document.querySelectorAll('.remove-good-btn').forEach(btn => {
                        btn.addEventListener('click', async () => {
                            const goodId = btn.getAttribute('data-goodid');
                            if (confirm('确定要下架该商品吗？')) {
                                await removeGood(goodId);
                            }
                        });
                    });
                }
            } catch (error) {
                console.error('加载商品失败:', error);
                alert('加载商品失败，请稍后重试');
            }
        }

        // 提交上架商品
        async function submitAddGood() {
            const goodData = {
                // goodid: parseInt(document.getElementById('goodId').value),
                goodname: document.getElementById('goodName').value,
                price: parseFloat(document.getElementById('goodPrice').value),
                good_desc: document.getElementById('goodDesc').value
            };
            
            try {
                const response = await fetch(`http://localhost:8080/api/goods/add?merchantId=${currentMerchant.id}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(goodData)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('商品上架成功！');
                    document.getElementById('addGoodModal').classList.add('hidden');
                    // 刷新商品列表
                    await loadMerchantGoods();
                } else {
                    alert('商品上架失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('上架商品失败:', error);
                alert('上架商品失败，请稍后重试');
            }
        }

        // 下架商品
        async function removeGood(goodId) {
            try {
                const response = await fetch(`http://localhost:8080/api/goods/remove?goodId=${goodId}&merchantId=${currentMerchant.id}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('商品下架成功！');
                    // 刷新商品列表
                    await loadMerchantGoods();
                } else {
                    alert('商品下架失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('下架商品失败:', error);
                alert('下架商品失败，请稍后重试');
            }
        }

        // 加载商家订单
        async function loadMerchantOrders() {
            try {
                const response = await fetch('http://localhost:8080/api/orders/merchant/owned', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(currentMerchant)
                });
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const goodsListElement = document.getElementById('goodsList');
                    goodsListElement.innerHTML = '';
                    
                    if (result.data.length === 0) {
                        goodsListElement.innerHTML = '<div class="col-span-full text-center py-8 text-gray-500">您暂无订单</div>';
                        return;
                    }
                    
                    result.data.forEach(order => {
                        const orderCard = document.createElement('div');
                        orderCard.className = 'border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition';
                        orderCard.innerHTML = `
                            <div class="p-4">
                                <div class="flex justify-between items-start mb-2">
                                    <h3 class="font-bold text-lg">订单 #${order.id}</h3>
                                    <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded">已完成</span>
                                </div>
                                <p class="text-gray-700 mb-1">商品: ${order.goodname}</p>
                                <p class="text-gray-700 mb-1">价格: ¥${order.price}</p>
                                <p class="text-gray-700 mb-1">买家: ${order.receiver_username || '未知'}</p>
                                <p class="text-gray-500 text-sm mt-2">下单时间: ${order.createtime ? new Date(order.createtime).toLocaleString('zh-CN', { 
                                    year: 'numeric', 
                                    month: '2-digit', 
                                    day: '2-digit', 
                                    hour: '2-digit', 
                                    minute: '2-digit', 
                                    second: '2-digit' 
                                }) : '未知'}</p>
                            </div>
                        `;
                        goodsListElement.appendChild(orderCard);
                    });
                }
            } catch (error) {
                console.error('加载订单失败:', error);
                alert('加载订单失败，请稍后重试');
            }
        }

        // 填充编辑店铺表单
        function fillEditShopForm() {
            document.getElementById('editMerchantId').value = currentMerchant.id;
            document.getElementById('editUsername').value = currentMerchant.username || '';
            document.getElementById('editShopname').value = currentMerchant.shopname || '';
            document.getElementById('editContactPerson').value = currentMerchant.contact_person || '';
            document.getElementById('editPhone').value = currentMerchant.phone || '';
            document.getElementById('editAddress').value = currentMerchant.address || '';
            document.getElementById('editShopDesc').value = currentMerchant.shop_desc || '';
            document.getElementById('editPassword').value = ''; // 密码不显示
        }

        // 提交编辑店铺资料
        async function submitEditShop() {
            const merchantData = {
                id: document.getElementById('editMerchantId').value,
                username: document.getElementById('editUsername').value,
                shopname: document.getElementById('editShopname').value,
                contact_person: document.getElementById('editContactPerson').value,
                phone: document.getElementById('editPhone').value,
                address: document.getElementById('editAddress').value,
                shop_desc: document.getElementById('editShopDesc').value
            };
            
            // 只有输入了密码才更新密码
            const password = document.getElementById('editPassword').value;
            if (password) {
                merchantData.password = password;
            }
            
            try {
                const response = await fetch('http://localhost:8080/api/merchant/update', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(merchantData)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 更新本地存储的商家信息
                    currentMerchant = { ...currentMerchant, ...merchantData };
                    localStorage.setItem('merchant', JSON.stringify(currentMerchant));
                    
                    // 更新页面显示
                    document.getElementById('merchantnameDisplay').textContent = currentMerchant.username;
                    document.getElementById('shopName').textContent = currentMerchant.shopname || '我的店铺';
                    document.getElementById('shopDesc').textContent = currentMerchant.shop_desc || '暂无店铺描述';
                    document.getElementById('shopAddress').textContent = currentMerchant.address || '暂无店铺地址';
                    
                    alert('店铺资料更新成功');
                    document.getElementById('editShopModal').classList.add('hidden');
                } else {
                    alert('店铺资料更新失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('更新店铺资料失败:', error);
                alert('更新店铺资料失败，请稍后重试');
            }
        }
    </script>
</body>
</html>